package com.jml;

import com.jml.filter.AddHeaderGatewayFilter;
import com.jml.filter.OneGatewayFilter;
import com.jml.filter.ThreeGatewayFilter;
import com.jml.filter.TwoGatewayFilter;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

@SpringBootApplication
public class GatewayConfigFilterApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayConfigFilterApplication.class, args);
    }
    /**
     * 配置类，替代yaml文件
     */
   /* @Bean
    public RouteLocator someRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(ps -> ps
                        .path("/**")//断言   url为“/”就直接跳转
                        .uri("https://www.baidu.com")//uri
                        .id("baidu_route"))//路由ID
                .build();
    }*/

    /**
     * 配置全局的负载均衡策略
     * @return
     */
    @Bean
    public IRule randomRule(){
        return new RandomRule();
    }

    //配置自定义多过滤器，让自定义过滤器生效，这个过滤器调用是一个责任链模式，
    // 分为前置过滤器好而后知过滤器  1-2-3-3-2-1
    @Bean
    public RouteLocator someRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(ps -> ps.path("/**")
                        .filters(fs ->
                                fs.filter(new OneGatewayFilter())
                                        .filter(new OneGatewayFilter())
                                        .filter(new TwoGatewayFilter())
                                        .filter(new ThreeGatewayFilter())
                                        .filter(new AddHeaderGatewayFilter())
                        ) // 配置自定义网关
                        .uri("http://localhost:8080")
                        .id("custom_filter"))
                .build();
    }

    //配置令牌桶算法的key:将主机名称作为限流key
    @Bean
    public KeyResolver keyResolver(){
        return exchange -> Mono.just(exchange .getRequest() .getRemoteAddress() .getHostName());
    }
}
